package com.xjh.him.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xjh.him.domain.UserDO;

import java.util.Date;

public class JwtUtil {
    private static final int DEFAULT_EXPIRE = 24 * 3600 * 1000;
    private static final String DEFAULT_SALT = "HIM_SIMPLE_CHAT";
    private static final Algorithm DEFAULT_ALG = Algorithm.HMAC256(DEFAULT_SALT);
    private static final JWTVerifier VERIFIER = JWT.require(DEFAULT_ALG).build();

    /**
     * 根据用户对象生成token
     * @param userDO
     * @return
     */
    public static String getToken(UserDO userDO) {
        long oneDayAfterMillis = System.currentTimeMillis() + DEFAULT_EXPIRE;
        return JWT.create()
                .withAudience(String.valueOf(userDO.getId()))
                .withExpiresAt(new Date(oneDayAfterMillis))
                .sign(Algorithm.HMAC256(DEFAULT_SALT));
    }

    /**
     * 解码获取用户id
     * @param token
     * @return
     * @throws Exception
     */
    public static Long decodeUserId(String token) throws Exception {
        DecodedJWT decodedJWT = VERIFIER.verify(token);
        String value = decodedJWT.getAudience().get(0);
        return Long.parseLong(value);
    }
}
